//获取应用实例
const app = getApp();
// 引入AES.js
var baseJs = require("../../common/base.js");
// 引入SDK核心类,实例化API核心类
var QQMapWX = require('../../common/qqmap-wx-jssdk.js');
var demo = new QQMapWX({
  key: 'b6af1635786ff310b0f07cba63460532' // 必填
});
var resultData = {};
var commodityAttr = [];
var attrValueList = [];
var currentPrice = '';
var currentNum = '';

// 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isArea: 0,
    isBuluoArea: 0,
    isEnjoyArea: 0,
    imgUrl: baseJs.imgUrl,
    // resultData: {},
    goodsId: 0,
    businessId: 0,
    type: 0,
    // 购买，底部弹出
    chooseFlag: true,
    // 兑换点信息
    checkFlag: true,
    // input默认是1
    num: 1,
    // 使用data数据对象设置样式名
    minusStatus: 'disabled',
    // 承诺
    promiseFlag: false,
    maskFlag: false,
    // 收藏
    color: '#999',
    collectData: [],
    top: [{
      'title': '商品',
      'active': true,
      'type': 0
    },
    {
      'title': '详情',
      'active': false,
      'type': 1
    }
    ],
    //轮播
    goodsLunbo: [],
    // 规格
    modelStr0: [],
    addCartOrNowBuy: "加入购物车",
    //支付
    buyType: "1",
    modelStr: "",
    orderInfo: "",
    // 导航
    map: "",
    // 
    uid: "",
    userType: "",
    name: '',
    firstIndex: "",
    // 提交订单
    buyGoods: "",
    // 填写价格-弹框
    peisongyoufei: '',
    hiddensubmit: true,
    nocancel: false,
    showModal: false,//选择自提/邮寄
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.setData({
      uid: wx.getStorageSync('uid'),
      userType: wx.getStorageSync('userType'),
      goodsId: options.goodsId,
      isArea: options.isArea,
      businessId: options.businessId,
      searchId: options.searchId,

    })
    this.GetGoodInfoByID();
  },
  onHide: function () {
    this.setData({
      showModal: false,
      chooseFlag: true
    })
  },
  // 分享
  onShareAppMessage: function (res) {
    var that = this;
    // 返回数据
    return {
      title: that.data.resultData.GoodsTitle,
      path: '/packageA/goodsDetail/goodsDetail?goodsId=' + that.data.resultData.goodsId,
      imageUrl: that.data.resultData.ImagesZhanshi,
      success: function (res) {
        wx.showToast({
          title: "转发成功",
          icon: 'none',
          duration: 2000
        });
      },
      fail: function (res) {
        wx.showToast({
          title: "转发失败",
          icon: 'none',
          duration: 2000
        });
      }
    }
  },
  // 顶部
  topTap: function (e) {
    var top = this.data.top;
    var type = e.currentTarget.dataset.type;
    for (var i = 0, len = top.length; i < len; ++i) {
      if (top[i].type == type) {
        top[i].active = true;
      } else {
        top[i].active = false
      }
    }
    this.setData({
      top: top,
      type: type
    })
    // console.log(type);
    // console.log(top);
  },
  //跳转到自由支付页面
  freepay() {
    wx.navigateTo({
      url: '/packageA/freePay/freePay',
    })
  },
  // 商品详情
  GetGoodInfoByID: function () {
    var that = this;
    var uid = this.data.uid;
    var goodsLunbo = this.data.goodsLunbo;
    var goodsId = this.data.goodsId;
    var businessId = this.data.businessId;
    // var resultData = this.data.resultData;
    var modelStr0 = this.data.modelStr0;
    var isBuluoArea = this.data.isBuluoArea;
    var isEnjoyArea = this.data.isEnjoyArea;
    var map = this.data.map;
    wx.showLoading({
      title: '加载中',
    })
    console.log(baseJs.api_Goods + "GetGoodsInfoByID" + "?" + "GoodsId=" + goodsId + "&UID=" + uid)
    wx.request({
      url: baseJs.api_Goods + "GetGoodsInfoByID" + "?" + "GoodsId=" + goodsId + "&UID=" + uid,
      success: function (res) {
        console.log(res);
        if (res.data.ResultData !== "") {
          resultData = res.data.ResultData;
          console.log(resultData)
          goodsLunbo = resultData.GoodsPic.split(';');
          goodsLunbo.splice(goodsLunbo.length - 1)
          // goodsLunbo = resultData.ImagesZhanshi;
          modelStr0 = resultData.NewModels;
          if (modelStr0.length < 1) {
            if (resultData.IsOpenLimitBuy == '1') {
              modelStr0 = '规格,件-' + resultData.LimitUserBuyNum + '-' + resultData.Price + '-' + resultData.RackPrice;
            } else {
              modelStr0 = '规格,件-' + resultData.StoreNum + '-' + resultData.Price + '-' + resultData.RackPrice;
            }
          }
          if (resultData.IsCollection == 1) { //改变收藏的颜色
            that.setData({
              color: "#f00"
            })
          } else {
            that.setData({
              color: "#999"
            })
          }
          isBuluoArea = resultData.IsDiscountArea;
          isEnjoyArea = resultData.IsEnjoyArea;
          map = resultData.DuihuanAddress;
          currentNum = resultData.StoreNum;
          currentPrice = resultData.Price;
          that.setData({
            resultData: resultData,
            goodsLunbo: goodsLunbo,
            businessId: resultData.SJId,
            map: map,
            modelStr0: modelStr0,
            currentNum: currentNum,
            currentPrice: currentPrice,
          })
          // console.log(currentNum);
          // console.log(isEnjoyArea);
          wx.hideLoading();
        } else {
          wx.showToast({
            icon: "error",
            title: res.data.ResultMsg,
          })
          // 详情出错，返回上一页面
          setTimeout(function () {
            wx.navigateBack()
          }, 1000)
        }
      }
    })
  },
  // 点击查看易易信用跳转到易易信用页面
  creditTap: function (e) {
    console.log(e);
    wx.navigateTo({
      url: '/packageA/yiyicredit/yiyicredit?SJID=' + e.currentTarget.dataset.sjid,
    })
  },
  // 点击轮播图放大
  previewImg(e) {
    wx.previewImage({
      current: e.currentTarget.dataset.value,
      urls: this.data.goodsLunbo
    })
  },


  // 底部弹出商品详情
  chooseTap0: function () {
    var that = this;
    this.data.addCartOrNowBuy = "加入购物车";
    // var commodityAttr = this.data.commodityAttr;
    commodityAttr = this.endModelArr(this.data.modelStr0);
    this.setData({
      chooseFlag: !this.data.chooseFlag,
      commodityAttr: commodityAttr,
    });
    this.setData({
      includeGroup: commodityAttr
    });
    this.distachAttrValue(this.data.commodityAttr);
    // 只有一个属性组合的时候默认选中 
    // console.log(this.data.attrValueList); 
    if (commodityAttr.length == 1) {
      for (var i = 0; i < commodityAttr[0].attrValueList.length; i++) {
        attrValueList[i].selectedValue = commodityAttr[0].attrValueList[i].attrValue;
      }
      this.setData({
        attrValueList: attrValueList
      });
    }




  },
  chooseTapBuy: function () {
    if (app.isLogin()) {
      var that = this;
      this.data.addCartOrNowBuy = "立即购买";
      // var commodityAttr = this.data.commodityAttr;
      commodityAttr = this.endModelArr(this.data.modelStr0);
      this.setData({
        chooseFlag: !this.data.chooseFlag,
        commodityAttr: commodityAttr,
      });
      this.setData({
        includeGroup: commodityAttr
      });
      this.distachAttrValue(this.data.commodityAttr);
      // 只有一个属性组合的时候默认选中 
      // console.log(this.data.attrValueList); 
      if (commodityAttr.length == 1) {
        for (var i = 0; i < commodityAttr[0].attrValueList.length; i++) {
          attrValueList[i].selectedValue = commodityAttr[0].attrValueList[i].attrValue;
        }
        this.setData({
          attrValueList: attrValueList
        });
      }
    }

  },
  // 点击-号
  bindMinus: function () {
    var num = this.data.num;
    if (num > 1) {
      num--;
    }
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  /* 点击加号 */
  bindPlus: function () {
    var num = this.data.num;
    if (currentNum > parseInt(num)) {
      // wx.showModal({
      //   title: '提示',
      //   content: '库存不足',
      //   showCancel: false
      // })
      num++;
    }
    if (currentNum < parseInt(num)) {
      num = currentNum
    }

    var minusStatus = num >= currentNum ? 'disabled' : 'normal';
    this.setData({
      num: num,
      minusStatus: minusStatus
    });

  },
  /* 输入框事件 */
  bindManual: function (e) {
    var num = e.detail.value;
    if (num > currentNum) {
      e.detail.value = currentNum;
      num = currentNum
    }
    if (num < 1) {
      e.detail.value = '1';
      num = '1'
    }
    this.setData({
      num: num
    });
  },

  //加入购物车弹框中的——点击——确定/立即购买
  submit: function (e) {
    if (app.isLogin()) {
      // this.data.resultData.LimitBuyNum
      if (this.data.resultData.IsOpenLimitBuy == "1" && this.data.num > this.data.resultData.LimitBuyNum - 0) {
        wx.showToast({
          title: '超出限购',
          icon: 'error',
          duration: 1500
        })
        return
      }
      var that = this;
      var uid = this.data.uid;
      var goodsId = this.data.goodsId;
      var businessId = this.data.businessId;
      var goodsPrice = this.data.resultData.Price;
      var num = this.data.num;
      var buyType = this.data.buyType;
      var modelStr = this.data.modelStr;
      var addCartOrNowBuy = this.data.addCartOrNowBuy;
      var orderInfo = this.data.orderInfo;

      if (parseInt(num) > parseInt(currentNum)) {
        wx.showToast({
          title: '库存不足',
          icon: 'error',
          duration: 1000
        })
        return;
      }
      if (i < attrValueList.length) {
        wx.showToast({
          title: '请完善属性',
          icon: 'loading',
          duration: 1000
        })
      } else {
        var value = [];
        var putString = '';
        for (var i = 0; i < attrValueList.length; i++) {
          if (!attrValueList[i].selectedValue) {
            break;
          }
          if (i == 0) {
            putString = attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
          } else {
            putString = putString + ';' + attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
          }
        }
        var model = putString;
        var GoodsID1 = '';
        var price1 = '';
        var stockNum1 = '';
        if (addCartOrNowBuy == "加入购物车") {
          // console.log("加入购物车");
          wx.request({
            url: baseJs.api + baseJs.encryUrl("method=AddShopCart&UID=" + uid + "&GoodsId=" + goodsId + "&SJID=" + businessId + "&PresentPrice=" + goodsPrice + "&BuyNum=" + num + "&Model=" + model + "&DeliverGoods=" + buyType),
            success: function (res) {
              console.log(JSON.parse(baseJs.decryUrl(res.data)));
              wx.showToast({
                title: JSON.parse(baseJs.decryUrl(res.data)).ResultMsg,
                icon: 'none',
                duration: 1000
              })
            }
          })
        } else {
          this.setData({
            showModal: true
          })
        }
      }
    }
  },

  common() {
    var putString = '';
    var uid = this.data.uid;
    var goodsId = this.data.goodsId;
    var businessId = this.data.businessId;
    var goodsPrice = this.data.resultData.Price;
    var num = this.data.num;
    var buyType = this.data.buyType;
    var modelStr = this.data.modelStr;
    var addCartOrNowBuy = this.data.addCartOrNowBuy;
    var orderInfo = this.data.orderInfo;
    for (var i = 0; i < attrValueList.length; i++) {
      if (!attrValueList[i].selectedValue) {
        break;
      }
      if (i == 0) {
        putString = attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
      } else {
        putString = putString + ';' + attrValueList[i].attrKey + ',' + attrValueList[i].selectedValue
      }
    }
    var model = putString;
    return {
      model, uid, goodsId, businessId, goodsPrice, num, buyType, modelStr, addCartOrNowBuy, orderInfo
    }
  },

  //自提
  kehuziti() {
    // console.log(this.common());
    var model = this.common()
    var uid = this.data.uid;
    var goodsId = this.data.goodsId;
    // var businessId = this.data.businessId;
    // var goodsPrice = this.data.resultData.Price;
    var num = this.data.num;
    // var buyType = this.data.buyType;
    // var modelStr = this.data.modelStr;
    // var addCartOrNowBuy = this.data.addCartOrNowBuy;
    // var orderInfo = this.data.orderInfo;
    // console.log("自提");
    // // console.log("立即购买");
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    buyGoods = goodsId + "-" + num + "-" + model
    // if (buyGoods.length < 1) {

    // } else {
    //   buyGoods = buyGoods + "~" + goodsId + "-" + num + "-" + value.join(';')
    // }
    // console.log(buyGoods)
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: '0',
        IsShouYinJiOrder: '0',
        IsZiTi: '1',
        Remark: '',
      }),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data)
        var json = res.data.ResultData;
        // console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/Orderpayment/Orderpayment?orderid=' + json.OrderId,
            })
          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },
  // 邮寄
  youji() {
    var uid = this.data.uid;
    var goodsId = this.data.goodsId;
    // var businessId = this.data.businessId;
    // var goodsPrice = this.data.resultData.Price;
    var num = this.data.num;
    // var buyType = this.data.buyType;
    // var modelStr = this.data.modelStr;
    // var addCartOrNowBuy = this.data.addCartOrNowBuy;
    // var orderInfo = this.data.orderInfo;
    var model = this.common()
    console.log("邮寄");
    var uid = wx.getStorageSync('uid');
    var buyGoods = '';
    buyGoods = goodsId + "-" + num + "-" + model
    wx.request({
      url: baseJs.api_Order + "SettlementOrder",
      method: 'post',
      data: baseJs.json2Form({
        UID: uid,
        BuyGoodsInfo: buyGoods,
        PeiSongYouFei: '0',
        IsShouYinJiOrder: '0',
        IsZiTi: '0',
        Remark: '',
      }),
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data)
        var json = res.data.ResultData;
        // console.log(json);
        if (res.data.ResultFlag == 1) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
          setTimeout(function () {
            wx.navigateTo({
              url: '/packageA/Orderpayment/Orderpayment?orderid=' + json.OrderId + "&show=1",
            })
          }, 1000)
        }
        if (res.data.ResultFlag == 0) {
          wx.showToast({
            title: res.data.ResultMsg,
            icon: 'none',
            duration: 2000
          });
        }
      }
    })
  },

  // },
  // 以下为商品规格相关函数
  endModelArr: function (str) {
    // console.log(str)
    // |颜色,红;尺码,x-库存-部落价-市场价
    if (typeof (str) !== "string") return;
    var arr = []; //声明一个空数组用于返回
    var arr1 = str.split("|"); //第一次截取，通过“ | ”截取
    for (var i = 0; i < arr1.length; i++) {
      var temparr = arr1[i].split("-");//颜色,红;尺码,x-库存-部落价-市场价

      var obj = {
        attrValueList: [],
        GoodsID: this.data.goodsId,
        price: temparr[2],
        stockNum: temparr[1],
        skukey: '',
      };
      //声明一个对象 保存第一层数据
      var arr2 = temparr[0].split(";"); //第二次截取，通过“ ； ”截取 颜色,红;尺码,x
      for (var j = 0; j < arr2.length; j++) {
        var arr3 = arr2[j].split(","); //第三次截取，通过“ ， ”截取
        var objs = {}; //声明一个对象，保存最底层数据
        objs.attrKey = arr3[0]; //添加key
        objs.attrValue = arr3[1]; //添加value

        // for (var k = 0; k < arr3.length; k++) {
        //   if (arr3[1].indexOf("-") !== -1) { //去除“ - ”后无用的字符
        //     arr3[1] = arr3[1].substring(0, arr3[1].indexOf("-"))
        //   }

        // }
        obj.attrValueList.push(objs); //保存key和value
      }
      for (var k = 0; k < obj.attrValueList.length; k++) {

        if (obj.skukey.length < 1) {
          obj.skukey = obj.attrValueList[k].attrKey + ',' + obj.attrValueList[k].attrValue
        } else {
          obj.skukey = obj.skukey + ';' + obj.attrValueList[k].attrKey + ',' + obj.attrValueList[k].attrValue
        }
      }
      // console.log(obj);
      arr.push(obj); //保存所有的key和value
    }
    return arr;
  },
  // 
  distachAttrValue: function (commodityAttr) {
    /** 
    将后台返回的数据组合成类似 
    { 
    attrKey:'型号', 
    attrValueList:['1','2','3'] 
    } 
    */
    // 把数据对象的数据（视图使用），写到局部内 
    attrValueList = [];
    // 遍历获取的数据 
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        var attrIndex = this.getAttrIndex(commodityAttr[i].attrValueList[j].attrKey, attrValueList);
        // console.log('属性索引', attrIndex); 
        // 如果还没有属性索引为-1，此时新增属性并设置属性值数组的第一个值；索引大于等于0，表示已存在的属性名的位置 
        if (attrIndex >= 0) {
          // 如果属性值数组中没有该值，push新值；否则不处理 
          if (!this.isValueExist(commodityAttr[i].attrValueList[j].attrValue, attrValueList[attrIndex].attrValues)) {
            attrValueList[attrIndex].attrValues.push(commodityAttr[i].attrValueList[j].attrValue);
          }
        } else {
          attrValueList.push({
            attrKey: commodityAttr[i].attrValueList[j].attrKey,
            attrValues: [commodityAttr[i].attrValueList[j].attrValue]
          });
        }
      }
    }
    // console.log('result', attrValueList) 
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].attrValueStatus) {
          attrValueList[i].attrValueStatus[j] = true;
        } else {
          attrValueList[i].attrValueStatus = [];
          attrValueList[i].attrValueStatus[j] = true;
        }
      }
    }
    this.setData({
      attrValueList: attrValueList
    });
  },
  getAttrIndex: function (attrName, attrValueList) {
    // 判断数组中的attrKey是否有该属性值 
    for (var i = 0; i < attrValueList.length; i++) {
      if (attrName == attrValueList[i].attrKey) {
        break;
      }
    }
    return i < attrValueList.length ? i : -1;
  },
  isValueExist: function (value, valueArr) {
    // 判断是否已有属性值 
    for (var i = 0; i < valueArr.length; i++) {
      if (valueArr[i] == value) {
        break;
      }
    }
    return i < valueArr.length;
  },

  //重新计算
  re_count: function () {
    var total_price = 0.00;
    selectgood.forEach(item => {
      total_price = total_price + parseFloat(item.BuyNum) * parseFloat(item.Price);
    });
    if (selectgood.length > 0) {
      cartpoint = '1'
    } else {
      cartpoint = '0'
    }
    this.setData({
      total_price: total_price,
      cartpoint: cartpoint,
    });
    // console.log(total_price)
  },
  /* 选择属性值事件 */
  selectAttrValue: function (e) {
    /*
    点选属性值，联动判断其他属性值是否可选
    {
      attrKey:'型号',
      attrValueList:['1','2','3'],
      selectedValue:'1',
      attrValueStatus:[true,true,true]
    }
    console.log(e.currentTarget.dataset);
    */

    var attrValueList = this.data.attrValueList;
    var index = e.currentTarget.dataset.index;//属性索引
    var key = e.currentTarget.dataset.key;
    var value = e.currentTarget.dataset.value;
    // console.log(attrValueList)
    // console.log(index)
    // console.log(key)
    // console.log(value)
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      if (e.currentTarget.dataset.selectedvalue == e.currentTarget.dataset.value) {
        // 取消选中
        this.disSelectValue(attrValueList, index, key, value);
      } else {
        // 选中
        this.selectValue(attrValueList, index, key, value);
      }
    }
    var value1 = [];
    for (var i = 0; i < attrValueList.length; i++) {
      if (!attrValueList[i].selectedValue) {
        break;
      }
      value1.push(attrValueList[i].selectedValue);
    }
    if (i < attrValueList.length) {
      currentNum = resultData.StoreNum;
      currentPrice = resultData.Price;

    } else {
      var tempModel = value1.join(';');
      for (var i = 0; i < commodityAttr.length; i++) {
        // console.log(commodityAttr[i].skukey + '11111' + model);
        // console.log(commodityAttr[i].skukey)
        // console.log(tempModel)
        if (commodityAttr[i].skukey == tempModel) {
          currentPrice = commodityAttr[i].price;
          currentNum = commodityAttr[i].stockNum;
        }
      }
    }
    // console.log(commodityAttr)
    // console.log(currentNum)
    this.setData({
      currentNum: currentNum,
      currentPrice: currentPrice,
    })
  },
  /* 选中 */
  selectValue: function (attrValueList, index, key, value, unselectStatus) {
    // console.log('firstIndex', this.data.firstIndex);
    var includeGroup = [];
    if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选
      var commodityAttr = this.data.commodityAttr;
      // 其他选中的属性值全都置空
      // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus);
      for (var i = 0; i < attrValueList.length; i++) {
        for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
          attrValueList[i].selectedValue = '';
        }
      }
    } else {
      var commodityAttr = this.data.includeGroup;
    }

    // console.log('选中', commodityAttr, index, key, value);
    for (var i = 0; i < commodityAttr.length; i++) {
      for (var j = 0; j < commodityAttr[i].attrValueList.length; j++) {
        if (commodityAttr[i].attrValueList[j].attrKey == key && commodityAttr[i].attrValueList[j].attrValue == value) {
          includeGroup.push(commodityAttr[i]);
        }
      }
    }
    attrValueList[index].selectedValue = value;

    // 判断属性是否可选
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = true;
      }
    }
    for (var k = 0; k < attrValueList.length; k++) {
      for (var i = 0; i < includeGroup.length; i++) {
        for (var j = 0; j < includeGroup[i].attrValueList.length; j++) {
          if (attrValueList[k].attrKey == includeGroup[i].attrValueList[j].attrKey) {
            for (var m = 0; m < attrValueList[k].attrValues.length; m++) {
              if (attrValueList[k].attrValues[m] == includeGroup[i].attrValueList[j].attrValue) {
                attrValueList[k].attrValueStatus[m] = true;
              }
            }
          }
        }
      }
    }
    // console.log('结果', attrValueList);
    this.setData({
      attrValueList: attrValueList,
      includeGroup: includeGroup
    });

    var count = 0;
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) {// 第一次选中，同属性的值都可选
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
  },
  /* 取消选中 */
  disSelectValue: function (attrValueList, index, key, value) {
    // var commodityAttr = this.data.commodityAttr;
    attrValueList[index].selectedValue = '';

    // 判断属性是否可选
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        attrValueList[i].attrValueStatus[j] = true;
      }
    }
    this.setData({
      includeGroup: commodityAttr,
      attrValueList: attrValueList
    });

    for (var i = 0; i < attrValueList.length; i++) {
      if (attrValueList[i].selectedValue) {
        this.selectValue(attrValueList, i, attrValueList[i].attrKey, attrValueList[i].selectedValue, true);
      }
    }
  },

  // 
  chooseTap1: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  // 
  iconClearTap: function () {
    this.setData({
      chooseFlag: !this.data.chooseFlag
    });
  },
  afterSale: function () {
    var that = this;
    var businessId = this.data.businessId;
    wx.navigateTo({
      url: '/packageA/afterSale/afterSale?businessId=' + businessId,
    })
  },
  // 查看兑换店信息
  checkInfoTap0: function () {
    this.setData({
      checkFlag: !this.data.checkFlag
    });
  },
  // 
  checkInfoTap1: function () {
    this.setData({
      checkFlag: !this.data.checkFlag
    });
  },
  // 
  checkInfoIcon: function () {
    this.setData({
      checkFlag: !this.data.checkFlag
    });
  },
  // 评价
  evaluateTap: function () {
    var that = this;
    var goodsId = this.data.goodsId;
    wx.navigateTo({
      url: '/packageA/evaluate/evaluate?goodsId=' + goodsId,
    })
  },
  // 店铺
  storeTap: function () {
    var that = this;
    var businessId = this.data.businessId;
    wx.navigateTo({
      url: '/packageA/store/store?businessId=' + businessId,
    })
  },
  // 兑换电话
  phoneCall: function () {
    var that = this;
    var resultData = this.data.resultData;
    var phoneNumber = resultData.DuihuanPhone;
    wx.makePhoneCall({
      phoneNumber: phoneNumber
    })
  },
  // 投诉
  complaint: function () {
    if (app.isLogin()) {
      var that = this;
      var businessId = this.data.businessId;
      wx.navigateTo({
        url: '/packageA/complaint/complaint?businessId=' + businessId,
      })
    }
  },
  // 点击评分跳转到投诉详情
  evaluateListTap: function () {
    var that = this;
    var businessId = this.data.businessId;
    wx.navigateTo({
      url: '/packageA/evaluatelist/evaluatelist?businessId=' + businessId,
    })
  },
  // 公众承诺
  promiseTap0: function () {
    this.setData({
      maskFlag: !this.data.maskFlag,
      promiseFlag: !this.data.promiseFlag
    });
  },
  // 
  promiseTap1: function () {
    this.setData({
      maskFlag: !this.data.maskFlag,
      promiseFlag: !this.data.promiseFlag
    });
  },
  // 收藏
  collectTap: function () {
    var that = this;
    if (app.isLogin())
      var uid = this.data.uid;
    var goodsId = this.data.goodsId;
    var collectData = this.data.collectData;
    // var color = this.data.color;
    wx.request({
      url: baseJs.api + baseJs.encryUrl("method=AddGoodsCollection&UID=" + uid + "&GoodsId=" + goodsId),
      success: function (res) {
        collectData = JSON.parse(baseJs.decryUrl(res.data)).ResultData;
        var msg = (JSON.parse(baseJs.decryUrl(res.data)))
        console.log(collectData);
        if (collectData == "" && msg.ResultFlag) {
          wx.showToast({
            title: '取消收藏成功',
            icon: "none"
          })
        }
        that.setData({
          collectData: collectData,
        })
        if (collectData.length != '') {
          that.setData({
            color: "#f00",
          })
        } else {
          that.setData({
            color: "#999",
          })
        }
      }
    })
  },
  // 规格
  getModelArr: function (modelStr) {
    var modelArr = [];
    for (var i = 0; i < modelStr.split('|')[0].split(';').length; i++) {
      var arr = {
        name: modelStr.split('|')[0].split(';')[i].split(',')[0],
        value: [modelStr.split('|')[0].split(';')[i].split(',')[1]]
      };
      modelArr.push(arr)
    }
    for (var m = 0; m < modelStr.split('|').length; m++) {
      for (var n = 0; n < modelStr.split('|')[m].split(';').length; n++) {
        if (m > 0) {
          modelArr[n].value.push(modelStr.split('|')[m].split(';')[n].split(',')[1])
        }
      }
    }
    return modelArr;
  },
  getModelList: function (modelStr) {
    var modelJsonArr = [];
    var modelJsonStr = '{"';
    for (var x = 0; x < modelStr.split('|').length; x++) {
      for (var y = 0; y < modelStr.split('|')[x].split(';').length; y++) {
        if (y == modelStr.split('|')[x].split(';').length - 1) {
          modelJsonStr += modelStr.split('|')[x].split(';')[y].split(',')[1].split('-')[0] + '":{stock:' + modelStr.split('|')[x].split(';')[y].split(',')[1].split('-')[1] + ',price1:' + modelStr.split('|')[x].split(';')[y].split(',')[1].split('-')[2] + ',price2:' + modelStr.split('|')[x].split(';')[y].split(',')[1].split('-')[3];
        } else {
          modelJsonStr += modelStr.split('|')[x].split(';')[y].split(',')[1].split('-')[0] + ';';
        }
      }
    }
    return modelJsonStr;
  },


  // 导航
  openMap: function () {
    var that = this;
    var map = this.data.map;
    // 调用接口
    demo.geocoder({
      address: map,
      success: function (res) {
        console.log(res);
        wx.openLocation({
          latitude: res.result.location.lat,
          longitude: res.result.location.lng,
          scale: 28
        })
      },
      fail: function (res) {
        // console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });

  },

  // 禁止屏幕滚动
  preventTouchMove: function () {
  },

  // 点击模板层
  clearMask() {
    this.setData({
      showModal: false
    })
  }
  //
})                                   